package com.findyou.proxy;

import com.findyou.service.AccountService;
import com.findyou.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Title: CglibProxyFactory
 * @Author 贾金博
 * @Package com.findyou.proxy
 * @Date 2024/11/29 上午9:21
 * @description: CGLIB动态代理方式
 */
@Component
public class CglibProxyFactory {

    @Autowired
    private AccountService accountService;

    @Autowired
    private TransactionManager transactionManager;

    // 通过 Cglib动态代理方式去拿到代理对象
    public AccountService createAccountServiceCglibProxy() {
        // 参数1：目标类的字节码对象
        // 参数2：动作类，当代理对象调用目标对象中原方法的时候 也都会去执行 intercept 翻译为 拦截
        AccountService accountServiceProxy  = (AccountService)Enhancer.create(accountService.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                Object result = null;
                try {
                    // 1.开启事务
                    transactionManager.beginTransaction();
                    // 2.业务操作
                    result = method.invoke(accountService, args);
                    // 3.提交事务
                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    // 4.回滚事务
                    transactionManager.rollback();
                } finally {
                    // 5.释放资源
                    transactionManager.release();
                }
                return result;
            }
        });
       return accountServiceProxy;
    }
}
